#!/usr/bin/env python
# -*-coding:UTF-8-*-
# Author: chenzuoqing@126.com
# Create: 2018/8/22 15:48
# File  : tasks.py

"""
celery发送邮件通知
"""

from celery import task
from devops.settings import EMAIL_FROM
from django.core.mail import EmailMultiAlternatives


@task
def send_mail(to_list, user, sql_id, remark, action_type, sql_content, db_name):
    """
    邮件html不支持加载js，可以把SQL语法的js高亮注释
    """

    html = """
    <html>
    <head>
        <link href="https://cdn.bootcss.com/highlight.js/9.10.0/styles/xcode.min.css" rel="stylesheet">
        <script src="http://cdn.bootcss.com/highlight.js/8.0/highlight.min.js"></script>
        <script>hljs.initHighlightingOnLoad();</script>
    </head>
    <body>
    <p style="margin-top: 20px">{}，SQL编号<i>{}</i>.</p>
    <div style="margin: 5px">
        <span style="width: 80px;text-align: right;display: inline-block;"><strong>操作人：</strong></span><span>{}</span><br>
        <span style="width: 80px;text-align: right;display: inline-block;"><strong>环境：</strong></span><span>生产环境</span><br>
        <span style="width: 80px;text-align: right;display: inline-block;"><strong>执行库：</strong></span><span>{}</span><br>
        <span style="width: 80px;text-align: right;display: inline-block;"><strong>备注：</strong></span><span>{}</span><br>
        <span style="width: 80px;text-align: right;display: inline-block;"><strong>SQL：</strong></span>
        <div style="margin-left: 70px">
            <pre style="margin: 0"><code style="font-family: Consolas;">{}</code></pre>
        </div>
    </div>
    </body>
    </html>
    """
    title = ''
    if action_type == '--enable-check':
        title = '提交了上线申请'
    elif action_type == '--enable-execute':
        title = '已执行上线语句'

    subject = '{} {} - {}'.format(user, title, sql_id)
    text_content = 'SQL上线通知'
    html_content = html.format(subject, sql_id, user, db_name, remark, sql_content)
    try:
        msg = EmailMultiAlternatives(subject, text_content, EMAIL_FROM, to_list)
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        return True
    except Exception as e:
        print(e)
        return False
